﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Migrator.Util;
using Migrator.Exceptions;
using Migrator.Entities;

namespace MigratorUI.UI
{
    public partial class LaptopOptionsForm : Form
    {
        public LaptopOptionsForm(Internet internet, List<Router> routersInRange)
        {
            InitializeComponent();

            this.internet = internet;
            foreach (Router router in routersInRange)
            {
                cmbNetworks.Items.Add(router.NetworkAddress.ToString());
            }

            cmbNetworks.SelectedIndex = 0;
        }

        public string MACAddress
        {
            get { return this.txtMACAddress.Text; }
        }

        public string NetworkAddress
        {
            get { return this.cmbNetworks.SelectedItem.ToString(); }
        }

        private bool Validate(out string errorMessages) 
        {
            errorMessages = "";
            try 
            {
                IPAddress address = new IPAddress(this.NetworkAddress);
            } 
            catch (InvalidAddressException)
            {
                errorMessages += "- Endereço IP inválido!\n";
            }

            try
            {
                MACAddress address = new MACAddress(this.MACAddress);
                if (this.internet.Contains(address))
                {
                    errorMessages += "- O endereço físico escolhido já está a ser usado!\n";
                }
            }
            catch (InvalidAddressException)
            {
                errorMessages += "- Endereço físico inválido!\n";
            }

            return errorMessages.Length == 0;
        }


        private void LaptopOptionsForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (this.DialogResult == DialogResult.OK)
            {
                string errorMessages;
                if (!this.Validate(out errorMessages))
                {
                    MessageBox.Show("Os seguintes erros foram encontrados:\n\n" + errorMessages, "Dados inválidos", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    e.Cancel = true;
                }
            }
        }

        private Internet internet;
    }
}
